var app = sm("do_App");
var page = sm("do_Page");
var nf = sm("do_Notification");
var pub = require("url/pub");
var http = require("helper/http");

//声明UI变量
var listview=ui("listview");
var listdata = mm("do_ListData");
listview.bindItems(listdata);//绑定item的数据
var noData = [{"template":1,"labelContent":"暂无评论"}];
/**********加载页头begin***********/
var headerAout = ui("headerAout");
var addheader = headerAout.add("header", "source://view/reuse/header.ui", 0, 0);
//左上角-返回
var headerLeft = ui(addheader+".headerLeft");
headerLeft.on("touch", function() {
	app.closePage();
});
ui(addheader+".labelTitle").text = "我的评论";
/**********加载页头end***********/
page.on("back", function() {
	app.closePage();
})

var pageNum = 1;
var httpUrl = pub.url.comment.managePage;

page.on("loaded", function(){
	getFirstPageData();
});

//全部刷新数据
function getFirstPageData(){
	pageNum = 1;
	var params={page:pageNum};
	http.post(httpUrl,params,function(data){
		listview.rebound();
		listdata.removeAll();
		var content = data.page.content;
		if(content.length){
			for(var i in content){
				if(content[i].hasImg){
					content[i].imgMain = content[i].imgItems[0].source;
				}
			}
			listdata.addData(content);
		}
		else{
			listdata.addData(noData);
		}
		listview.refreshItems();//刷新item数据
	});
}

//刷新数据
function getNextPageData() {
	pageNum++;
	var params={page:pageNum};
	http.post(httpUrl,params,function(data){
		listview.rebound();
		var content = data.page.content;
		if(content.length){
			for(var i in content){
				if(content[i].hasImg){
					content[i].imgMain = content[i].imgItems[0].source;
				}
			}
		}
		listdata.addData(content);
		listview.refreshItems();//刷新item数据
	});
}
//下拉列表，刷新数据
listview.on("pull", function(data){
	if (data.state == 2){
		getFirstPageData();
	}
});

//上拉列表，翻页数据
listview.on("push", function(data){
	if (data.state == 2){
		getNextPageData();
	}
});

page.on("deleteMessage", function(data) {
	var alldata = listdata.getRange(0);
	for(var i = 0;i<alldata.length;i++){
		if(alldata[i].id==data){
			listdata.removeData([i]);
			listview.refreshItems();
			break;
		}
	}
	if(alldata.length==1){
		listdata.addData(noData);
		listview.refreshItems();
	}
})
